package com.taolili.demo.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.taolili.demo.common.R;
import com.taolili.demo.entity.BalanceRecord;
import com.taolili.demo.entity.UserBalance;
import com.taolili.demo.service.BalanceRecordService;
import com.taolili.demo.service.UserBalanceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 余额管理
 */
@Slf4j
@RestController
@RequestMapping("/record")
public class BalanceController {

    @Autowired
    private UserBalanceService userBalanceService;
    @Autowired
    private BalanceRecordService balanceRecordService;

    /**
     * 查询用户钱包余额
     */
    @GetMapping("/id")
    public R get(@PathVariable Long id) {
        UserBalance userBalance = userBalanceService.getById(id);
        if (userBalance != null) {
            Integer balance = userBalance.getBalance();
            return R.success(balance);
        } else {
            return R.error("该用户不存在");
        }
    }

    /**
     * 用户消费和退款功能
     * 可修改用户余额数据
     */
    @GetMapping("/Consumption")
    public R Consumption(@PathVariable Integer id ,Integer money) {
        //传入用户id 和 消费的金额money
        UserBalance userBalance = userBalanceService.getById(id);
        if (userBalance != null) {
            //减去消费的金额数
            userBalance.setBalance(userBalance.getBalance()-money);
            //更新消费数据
            userBalanceService.updateById(userBalance);
            //更新消费记录
            BalanceRecord balanceRecord = new BalanceRecord();
            balanceRecord.setId(id);
            balanceRecord.setBalanceRecord(money);
            balanceRecordService.save(balanceRecord);

            return R.success("更新成功");
        } else {
            return R.error("该用户不存在");
        }
    }

    /**
     * 查询用户钱包余额,分页显示
     */
    @GetMapping("/sc")
    public R selectConsumption(@PathVariable Integer id) {
        //分页构造器
        Page<BalanceRecord> pageInfo = new Page<>();
        //构建查询条件
        LambdaQueryWrapper<BalanceRecord> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //根据更新时间排序
        lambdaQueryWrapper.orderByAsc(BalanceRecord::getUpdatetime);
        balanceRecordService.page(pageInfo,lambdaQueryWrapper);

        return R.success(pageInfo);
    }




}
